﻿/* ----------------------------------------------------------------------------
 * Copyright (c) Philip Stears 
 *
 * This source code is subject to terms and conditions of the Microsoft Public 
 * License (Ms-PL).
 * 
 * By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 * 
 * To request a copy of the Microsoft Public License, send a request by email
 * to license@connectbasic.net.
 *
 * This notice must not be removed from this software.
 * ---------------------------------------------------------------------------- */

namespace ConnectBasic.Shell.Implementation.DefaultProjectInternals
{
    using System;
    using ConnectBasic.Shell.Extensibility;
    using Microsoft.Scripting;
    using Microsoft.Scripting.Hosting;
    
    internal class StandardModuleCodeServices
        : IServiceProvider
    {
        private ScriptEngine mEngine;
        private ScriptSource mSource;
        private ICodeSnapshot mSnapshot;       

        #region .ctor

        internal StandardModuleCodeServices(ScriptEngine engine, ICodeSnapshot snapshot)
        {
            mEngine = engine;
            mSnapshot = snapshot;

            // Load the source into a ScriptSource as that is
            // what the DLR uses everywhere
            mSource = engine.CreateScriptSourceFromString(snapshot.GetBufferContents(), "Main.bas", SourceCodeKind.File);
        }

        #endregion

        #region IServiceProvider Members

        public object GetService(Type serviceType)
        {
            if (serviceType == typeof(ICategorizer))
            {

                // Get hold of a token categorizer for the engine
                var categorizer = mEngine.GetService<TokenCategorizer>();

                if (categorizer != null)
                {

                    // Okay, we got a categorizer, give it the source code and return it
                    // wrapped in an implementation of ICategorizer
                    categorizer.Initialize(null, mSource, SourceLocation.MinValue);
                    return new DlrCategorizer(categorizer);
                }
            }

            // No match
            return null;
        }

        #endregion

    }
}
